import {
  regNoNegativeNumberFloat,
  regFloatOrIntegerPrice,
  regPositiveNumber,
  regQuantityFloat,
  regFloat,
  regHttpOrHttpsFront
} from "./regulars";

/**
 * 时间戳转日期
 * @param {String} types 转换类型
 * @param {String} timestamp 时间戳
 */
export const timestampToDate = (timestamp, types) => {
  // 补全为13位
  let arrTimestamp = (timestamp + "").split("");
  for (var start = 0; start < 13; start++) {
    if (!arrTimestamp[start]) {
      arrTimestamp[start] = "0";
    }
  }
  timestamp = arrTimestamp.join("") * 1;
  let date = new Date(timestamp);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hours = date.getHours();
  let minutes = date.getMinutes();
  let seconds = date.getSeconds();

  switch (types) {
    case "YY-MM-DD":
      return year + "-" + zero(month) + "-" + zero(day);
    case "YY年MM月DD日":
      return year + "年" + zero(month) + "月" + zero(day) + "日";
    case "YY年MM月DD日 HH:MM":
      return (
        year +
        "年" +
        zero(month) +
        "月" +
        zero(day) +
        "日" +
        " " +
        zero(hours) +
        ":" +
        zero(minutes)
      );
    case "HH:MM":
      return zero(hours) + ":" + zero(minutes);
    case "HH-MM":
      return zero(hours) + "-" + zero(minutes);
    case "HH:MM:SS":
      return zero(hours) + ":" + zero(minutes) + ":" + zero(seconds);
    case "HH:MM-HH:MM":
      return (
        zero(hours) +
        ":" +
        zero(minutes) +
        "-" +
        zero(hours) +
        ":" +
        zero(minutes)
      );
    case "MM月DD日":
      return zero(month) + "月" + zero(day) + "日";
    //YY-MM-DD HH:MM
    default:
      return (
        year +
        "-" +
        zero(month) +
        "-" +
        zero(day) +
        " " +
        zero(hours) +
        ":" +
        zero(minutes)
      );
  }
};

/**
 * 时间戳转时分秒
 * @times:今天剩余多少秒
 */
export const timeStampToHMS = (times) => {
  let hours = Math.floor(times / 3600);
  let minutes = Math.floor((times % 3600) / 60);
  let seconds = Math.ceil(times % 60);
  let Times = zero(hours) + ":" + zero(minutes) + ":" + zero(seconds);
  return Times;
};

/**
 * @获取当前时间，年月日
 * @ttype {String} 返回格式类型
 */
export const getThisTime = (ttype) => {
  let date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1,
    day = date.getDate(),
    h = date.getHours(),
    m = date.getMinutes();

  switch (ttype) {
    case "YY.MM.DD":
      return year + "." + zero(month) + "." + zero(day);
    case "YY.MM.DD HH:MM":
      return (
        year +
        "." +
        zero(month) +
        "." +
        zero(day) +
        " " +
        zero(h) +
        ":" +
        zero(m)
      );
    case "YY/MM/DD HH:MM":
      return (
        year +
        "/" +
        zero(month) +
        "/" +
        zero(day) +
        " " +
        zero(h) +
        ":" +
        zero(m)
      );
    case "YY-MM-DD HH:MM":
      return (
        year +
        "-" +
        zero(month) +
        "-" +
        zero(day) +
        " " +
        zero(h) +
        ":" +
        zero(m)
      );
    case "YY-MM-DD":
      return year + "-" + zero(month) + "-" + zero(day);
    case "YY-MM":
      return year + "-" + zero(month);
    case "YYMMDD":
      return year + zero(month) + zero(day);
    default:
      return year + "" + zero(month) + "" + zero(day);
  }
};

//数值补0方法
const zero = (value) => {
  if (value < 10) return "0" + value;
  return value;
};

/**
 * 时间戳转日期
 * @param {Number} timestamp 时间戳
 */
export const formatMsgTimeBlobal = (timestamp) => {
  // 补全为13位
  var arrTimestamp = (timestamp + "").split("");
  for (var i = 0; i < 13; i++) {
    if (!arrTimestamp[i]) {
      arrTimestamp[i] = "0";
    }
  }
  timestamp = arrTimestamp.join("") * 1;

  let minute = 1000 * 60;
  let hour = minute * 60;
  let day = hour * 24;
  let month = day * 30;
  let now = new Date().getTime();
  let yearN = new Date().getFullYear(); //当前年份
  let diffValue = now - timestamp;

  // 计算差异时间量级
  let monthC = diffValue / month;
  let weekC = diffValue / (7 * day);
  let dayC = diffValue / day;
  let hourC = diffValue / hour;
  let minC = diffValue / minute;
  let date = new Date(timestamp);

  let yearS = date.getFullYear();
  let monthS = date.getMonth() + 1;
  let dayS = date.getDate();
  let hoursS = date.getHours();
  let minuteS = date.getMinutes();

  const returnWeek = (dayC) => {
    //今天内
    if (dayC < 1) {
      return `${zero(hoursS)}:${zero(minuteS)}`;
    } else if (dayC > 1 && dayC < 2) {
      return `昨天`;
    } else {
      return `${zero(monthS)}月${zero(dayS)}日`;
    }
  };

  if (parseInt(yearS) !== parseInt(yearN)) {
    // 超过1年，直接显示年月日
    return yearS + "年" + zero(monthS) + "月" + zero(dayS) + "日";
  } else if (monthC >= 1 || weekC >= 1) {
    return `${zero(monthS)}月${zero(dayS)}日`;
  } else if (dayC > 0 && dayC < 7) {
    return returnWeek(dayC);
  } else if (hourC >= 1) {
    return `${zero(hoursS)}:${zero(minuteS)}`;
  } else if (minC >= 1) {
    return parseInt(minC) + "分钟前";
  }
  return "刚刚";
};

/**
 * 对象合并
 * @param {Object} obj1 对象1
 * @param {Object} obj2 对象2
 */
export const assign = (obj1, obj2 = {}) => {
  for (var name in obj1) {
    if (typeof obj1[name] === "object") {
      //先判断一下obj[name]是不是一个对象
      obj2[name] = obj1[name].constructor === Array ? [] : {}; //我们让要复制的对象的name项=数组或者是json
      copy(obj1[name], obj2[name]); //然后来无限调用函数自己 递归思想
    } else {
      obj2[name] = obj1[name]; //如果不是对象，直接等于即可，不会发生引用。
    }
  }
  return obj2; //然后在把复制好的对象给return出去
};

/**
 * 不能输入表情
 * @param {String} value 用户输入文本
 */
export const regEmoji = (value) => {
  if (app.globalData.biaoqingReg.test(value)) {
    wx.showToast({
      title: "不允许输入表情",
      icon: "none",
    });
    value = value.replace(app.globalData.biaoqingReg, "");
    value = value.replace(/\s+/g, "");
    console.log(value);
    return value;
  } else {
    return value;
  }
};

/**
 * 10000 => "10,000"
 * @param {number} num
 */
export const toThousandFilter = (num) => {
  return (+num || 0)
    .toString()
    .replace(/^-?\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+$)/g, ","));
};

/**
 * "10,000"=>10000
 * @param {String} num
 */
export const removeFormatMoney = (num) => {
  return parseFloat(num.replace(/[^\d\.-]/g, ""));
};

/**
 * 判断数字是不是正浮点数
 */
export const checkAfterTwo = (num) => {
  let zhengFloat = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
  if (zhengFloat.test(num)) {
    if (Number(num) != NaN) {
      return true;
    }
  }
  if (num == 0) {
    return true;
  }
  return false;
};
/**
 *  过滤浮点数后面只有两位小数
 */
export const getFloatNumberLaterTwoDigits = (num) => {
  let point_reg = /^./;
  let arr = [],
    arr2 = [],
    str1 = "",
    str2 = "";
  num = String(num);
  if (num == "0") return num;
  if (point_reg.test(num)) {
    arr = num.split(".");
    if (arr.length > 1 && arr[1].length > 1) {
      arr2 = arr[1].split("");
      //小数位至少2个
      let t2 = 0;
      if (arr2.length > 2) {
        let t3 = parseInt(arr2[2]); //如果第三位大于5，向前进1
        t2 = t3 > 5 ? parseInt(arr2[1]) + 1 : parseInt(arr2[1]);
      }

      if (parseInt(arr2[0]) > 0 || parseInt(arr2[1]) > 0) {
        str1 = String(arr2[0]) + String(arr2[1]);
        str2 = String(arr[0]) + "." + str1;
      } else {
        if (parseInt(arr2[0]) <= 0 && parseInt(arr2[1]) <= 0) {
          str2 = String(arr[0]);
        }
      }
      return str2;
    }
    return num;
  }
  return num;
};
/**
 * 过滤金额（浮点数或整数），将小数点后两位为零的过滤为正整数，如果不为零则保留
 */
export const filterPrice = (price) => {
  if (regFloatOrIntegerPrice.test(price)) {
    //浮点数
    if (regFloat.test(price)) {
      // console.log('浮点数', price);
      price = parseFloat(price);
      return parseFloat(price.toFixed(2));
    }
    // 非零开头的正整数
    if (regNoNegativeNumberFloat.test(price)) {
      // console.log('非零开头的正整数=>',price);
      price = parseFloat(price);
      return price;
    }
    throw `${price} 金额格式错误`;
  } else {
    throw `${price} price应该是一个浮点数或整数`;
  }
};

/**
 * 过滤直接显示的金额
 */
export const filterShowPrice = (price) => {
  if (regFloatOrIntegerPrice.test(price)) {
    //浮点数
    if (regFloat.test(price)) {
      // console.log('浮点数', price);
      price = parseFloat(price);
      return parseFloat(price.toFixed(2));
    }
    // 非零开头的正整数
    if (regNoNegativeNumberFloat.test(price)) {
      // console.log('非零开头的正整数=>',price);
      price = parseFloat(price);
      return price;
    }
    throw `${price} 金额格式错误`;
  } else {
    throw `${price} price应该是一个浮点数或整数`;
  }
};

/**
 * 验证输入的价格是否合法
 * 1.如果是正整数，不能以零开头
 * 2.如果是浮点数且小数点前面的位数超过两位的，不能以零开头
 * 3.只能有一个小数点
 */
export const checkPrice = (price) => {
  if (!regNoNegativeNumberFloat.test(price)) {
    return false;
  }
  //直接返回0或正整数
  if (regPositiveNumber.test(price)) {
    // console.log('直接返回0或正整数', price);
    return true;
  }
  //正小数
  if (regQuantityFloat.test(price)) {
    // console.log('正小数', price);
    return true;
  }
  return false;
};

/**
 * 按照减号分割金额，返回不带减号的金额
 */
export const accordanceReductionSplitPrice = (price) => {
  let _price = price.toString().split("-");
  return _price[1];
};

/**
 * 按照点分割金额，判断金额是否合法
 */
export const accordancePointSplitPrice = (price) => {
  let _price = price.split(".");
  if (_price.length > 2) {
    return false;
  }
  return true;
};

/**
 * 获取两日期之间日期列表函数
 * @param {String} stime 开始日期 '2018-07-25'
 * @param {String} etime 结束日期 '2018-08-02'
 */
export const getDiffDate = (stime, etime) => {
  //初始化日期列表，数组
  let diffdate = new Array();
  let i = 0;
  //开始日期小于等于结束日期,并循环
  while (stime <= etime) {
    diffdate[i] = stime;

    //获取开始日期时间戳
    let stime_ts = new Date(stime).getTime();
    // console.log('当前日期：' + stime + '当前时间戳：' + stime_ts);

    //增加一天时间戳后的日期
    let next_date = stime_ts + 24 * 60 * 60 * 1000;

    //拼接年月日，这里的月份会返回（0-11），所以要+1
    let next_dates_y = new Date(next_date).getFullYear() + "-";
    let next_dates_m =
      new Date(next_date).getMonth() + 1 < 10
        ? "0" + (new Date(next_date).getMonth() + 1) + "-"
        : new Date(next_date).getMonth() + 1 + "-";
    let next_dates_d =
      new Date(next_date).getDate() < 10
        ? "0" + new Date(next_date).getDate()
        : new Date(next_date).getDate();

    stime = next_dates_y + next_dates_m + next_dates_d;

    //增加数组key
    i++;
  }

  return diffdate;
};

export const isEmpty = (str) => {
  return (str === null || str === "" || str === undefined || JSON.stringify(str) === "{}" || str == 'undefined' || str.length == 0);
};

/**
 * 图片等比缩放
 * @param {Number} imgWidth 原图片宽度
 * @param {Number} imgHeight 原图片高度
 * @param {Number} containerWidth 图片容器宽度
 * @param {Number} containerHeight 图片容器高度
 * @returns 
 */
export function imageScaling(imgWidth, imgHeight, containerWidth, containerHeight) {
  let tempWidth = containerWidth;
  let tempHeight = containerHeight;
  let direction = '未知';
  let longShot = false; //是否是长截图

  imgWidth = parseFloat(imgWidth);
  imgHeight = parseFloat(imgHeight);
  containerWidth = parseFloat(containerWidth);
  containerHeight = parseFloat(containerHeight);

  if (imgWidth > 0 && imgHeight > 0) {
    //分辨率太小的图片，设置一个最小宽高
    if (imgWidth < 200 && imgHeight < 200) {
      imgWidth = 200;
      imgHeight = 200;
    }

    //原图片宽高比 > 容器宽高比，则原图片的宽度大于高度，即图片是横图
    if (imgWidth / imgHeight >= containerWidth / containerHeight) {
      if (imgWidth > containerWidth) {
        tempWidth = containerWidth;
        // 按原图片的比例进行缩放
        tempHeight = (imgHeight * containerWidth) / imgWidth;
      } else {
        // 按照图片的大小进行缩放
        tempWidth = imgWidth;
        tempHeight = imgHeight;
      }
      direction = '横图';

    } else {
      // 原图片的高度必然大于宽度，即图片是竖图
      // 宽高比小于0.3的，是相对较长的长截图，显示时按照容器宽高来cover显示
      if ((imgWidth / imgHeight) < 0.3) {
        longShot = true;
      } else {
        if (imgHeight > containerHeight) {
          tempHeight = containerHeight;
          // 按原图片的比例进行缩放
          tempWidth = (imgWidth * containerHeight) / imgHeight;
        } else {
          // 按原图片的大小进行缩放
          tempWidth = imgWidth;
          tempHeight = imgHeight;
        }
      }
      direction = '竖图';
    }
  }

  return { tempWidth: Math.ceil(tempWidth), tempHeight: Math.ceil(tempHeight), direction, longShot }
}


/**
 * 处理文本含有连续数字/字母时，整行换行问题
 * 实现办法：给文本每一个字符增加一个宽度为0的字符，虽然宽度增加一倍，但不影响
 * Array.from()可以处理有表情符号的情况
 * .split('')会导致表情符号乱码
 * @param {String} text
 * @returns
 */
export function extendedText(text) {
  return Array.from(text).join('\u{200B}');
}

/**
 * 判断手动维护的路由数组中是否已有某个路由
 * @param {Array} routes 路由数组
 * @param {String} name 路由名称
 * @returns routes
 */
export function checkHasRouteName(routes, name) {
  if (routes && routes.length > 0) {
    if (routes.indexOf(name) < 0) {
      routes.push(name);
    }
  }
  else {
    routes = [name]
  }
  return routes;
}

/**
 * 判断数组对象中是否已有某个路由方法
 * @param {Array} routes [{route:'A',callBack:func}]
 * @param {Object} arrayMehtod {route:'B',callBack:func}
 * @returns routes
 */
export function checkHasMethod(routes, arrayMehtod) {
  if (routes && routes.length > 0) {
    let _routes = [];
    routes.map(item => {
      _routes.push(item.route)
    })
    if (_routes.indexOf(arrayMehtod.route) < 0) {
      routes.push(arrayMehtod);
    }
  }
  else {
    routes = [arrayMehtod]
  }
  return routes;
}

/**
 * 校验图片地址为https/http
 * @param {Array} imgs [{url:'',...},...]，url为图片地址
 * @returns {
 *  check:true, //是否全部为有效的地址
 *  failIndex: '1,2,6' //非有效地址的索引
 * }
 */
export function checkImageUrl(imgs) {
  let index = 0, arr = [];
  if (imgs && imgs.length > 0) {
    for (let a = 0; a < imgs.length; a++) {
      if (regHttpOrHttpsFront.test(imgs[a].url)) {
        index++;
      } else {
        arr.push(a + 1)
      }
    }
  }
  return {
    check: imgs.length == index,
    failIndex: arr.join(',')
  };
}

/**
 * 判断预约类型单一
 * @param {Object} opts 
 * @param {Array} list 预约类型数组
 * @param {Number} type 要判定的类型
 * return boolean
 */
export function onlyFaceDiagnose(opts) {
  const {
    list,
    type
  } = opts;
  for (let a = 0; a < list.length; a++) {
    if (list[a] != type) {
      return false
    }
  }
  return true
}

/**
 * 统计各个预约类型的个数
 * @param {Array} list 项目列表
 * @param {String} key 选中项的key
 * 
 */
export function statisticalBookingTypeCount(opts) {
  const {
    list,
    key
  } = opts;
  let a = 0,
    b = 0,
    c = 0,
    d = 0;
  //is_faceseeing： 项目类型，0-治疗+面诊；1-面诊；2-直播半价；3-先做后付
  if (list.length > 0) {
    list.map(item => {
      if (key) {
        if (item[key]) {
          switch (parseInt(item.is_faceseeing)) {
            case 0:
              a++;
              break;
            case 1:
              b++;
              break;
            case 2:
              c++;
              break;
            case 3:
              d++;
              break;
          }
        }
      } else {
        switch (parseInt(item.is_faceseeing)) {
          case 0:
            a++;
            break;
          case 1:
            b++;
            break;
          case 2:
            c++;
            break;
          case 3:
            d++;
            break;
        }
      }
    })
  }
  return {
    cure: a,
    face: b,
    live: c,
    later: d,
  }
}

/**
 * 删除手动维护路由名称中的一个
 * 场景：页面退出后，从手动维护的路由名称中删除当前
 * @param {Obejct} opts 
 * @routes {Array} [A,B,C,...] 手动维护的路由数组
 * @name {String} 要删除的路由名称
 */
export function deleteUseRouteStackOne(opts) {
  const { routes, name } = opts;
  if (routes && routes.length > 0) {
    let _index = routes.indexOf(name);
    if (_index >= 0) {
      routes.splice(_index, 1)
    }
  }
  return routes
}